package com.ayuan.blog.common.wechat.common;

import com.ayuan.blog.common.httpclient.HTTPClientUtils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.log4j.Log4j2;

import javax.ws.rs.HttpMethod;
import java.io.IOException;

/**
 * Created by xiaozhu on 16/5/10.
 */
@Log4j2
public class WeChatBaseUtil{

    public static ObjectMapper objectMapper = new ObjectMapper();
    static {
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 不抛出未知属性异常
    }

    /**
     * 调用微信接口通用方法,如果返回结果errcode非0则抛出包含微信异常信息的runtime异常
     * @param token 微信token
     * @param bean 输入参数
     * @param url 微信接口地址
     * @param returnClass 微信返回结果对应的java类型(WeChatResponse类的子类)
     * @param <T>
     * @return
     */
    public static <T extends WeChatResponse> T sendWeChatHTTPRequest(String token, Object bean, String url, Class<T> returnClass) {
        T returnBean = null;
        ObjectNode response = null;
        try {
            try {
                response = HTTPClientUtils.sendHTTPRequest(String.format(url, token), null,
                        objectMapper.writeValueAsString(bean), HttpMethod.POST);
                log.info(response);
                returnBean = objectMapper.readValue(response.toString(), returnClass);
            } catch (IOException e) {
                throw new WechatException(WechatReturnCode.LOCAL_ERROR_001, e);
            }
            checkWeChatResult(returnBean.getErrcode(), returnBean.getErrmsg());
        } catch (WechatException e) {
            log.error("params:");
            log.error("token: " + token);
            log.error("bean: " + bean);
            log.error("url: " + url);
            log.error("returnClass: " + returnClass);
            log.error("response: " + response);
            if (e.getErrorCode() != null) {
                log.error("errCode: " + e.getErrorCode().getCode());
                log.error("errMsg: " + e.getErrorCode().getMsg());
            } else {
                log.error("errCode: " + e.getErrCode());
                log.error("errMsg: " + e.getMessage());
            }

            log.error(e.getMessage(), e);
            throw e;
        }
        return returnBean;
    }

    /**
     * 检查微信返回结果,如果errCode不是0则跑出包含相应错误信息的runtime异常(WechatException)
     * @param errCode
     * @param msg
     */
    public static void checkWeChatResult(int errCode, String msg) {
        if (0 != errCode) {
            WechatReturnCode wechatReturnCode = null;
            if (-1 == errCode) {
                wechatReturnCode = WechatReturnCode.CODE_S1;
            } else {
                try {
                    wechatReturnCode = WechatReturnCode.valueOf("CODE_" + errCode);
                } catch (Exception e) {
                    log.error("errCode : " + errCode);
                    log.error("errMsg : " + msg);
                    e.printStackTrace();
                }
            }
            if (wechatReturnCode != null) {
                throw new WechatException(wechatReturnCode);
            } else {
                throw new WechatException(String.valueOf(errCode), msg);
            }
        }
    }

}

